package com.wisdom.view;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.app.TabActivity;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TabWidget;
import android.widget.TextView;

import com.hisun.phone.core.voice.Log4Util;
import com.wisdom.MainActivity;
import org.sipdroid.sipua.R;
import org.sipdroid.sipua.ui.Receiver;
import org.sipdroid.sipua.ui.Settings;

import com.wisdom.VoiceApplication;
import com.wisdom.other.SystemScreenInfo;
import com.wisdom.tools.CCPConfig;
import com.wisdom.ui.AnimationTabHost;
import com.wisdom.voip.VoiceHelper;

public class HomeTabHostActivity extends TabActivity {
	private AnimationTabHost mTabHost;
	private TabWidget mTabWidget;
	private ImageView cursor;
	private int offset=0;
	private int currIndex=0;
	private int bmpW;
	private ImageView[] views;
    private ProgressDialog mDialog;
	public static final int WHAT_INIT_ERROR = 0x201C;

	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main_hometabhost);
		SystemScreenInfo.getSystemInfo(HomeTabHostActivity.this);
		InitImageView();
		mTabWidget=(TabWidget)findViewById(android.R.id.tabs);
		mTabHost=(AnimationTabHost)findViewById(android.R.id.tabhost);
		new Handler().postDelayed(new Runnable(){
			@Override
			public void run() {
				initBottomMenu();
			}
		},300);
		init();
		//查看是否登录过，否则先注册登录
		if(!PreferenceManager.getDefaultSharedPreferences(Receiver.mContext).getString(Settings.PREF_USERNAME, "").equals("")){
		//if(CCPConfig.check()){
			System.out.print("CCPConfig.check()==true");
			/*VoiceHelper voiceHelper=VoiceApplication.getInstance().getVoiceHelper();
			if(voiceHelper!=null&&voiceHelper.getDevice()!=null){
				
			}else{
			//初始化云通讯的设备
			mDialog = new ProgressDialog(HomeTabHostActivity.this);
			mDialog.setMessage(getString(R.string.dialog_message_text));
			mDialog.setCanceledOnTouchOutside(false);
			mDialog.show();
			new SDKInitAsyncTask().execute();
			}*/
		}
		else{
		//	if(!CCPConfig.getConfigProperties().get("step").toString().equals("1"))
			startActivity(new Intent(HomeTabHostActivity.this,WelcomeActivity.class));
		}
	}
	void showInitErrDialog(){
		new AlertDialog.Builder(this).setTitle(R.string.str_dialog_init_error_title)
				.setMessage(R.string.str_dialog_init_error_message)
				.setPositiveButton(R.string.dialog_btn,null).create().show();
	}
	
	class SDKInitAsyncTask extends AsyncTask<Void, Void, Void>{

		@Override
		protected Void doInBackground(Void... params) {
			VoiceApplication va= VoiceApplication.getInstance();
			va.initVoiceHelper(helperHandler);
			return null;
		}
		@Override
		protected void onPostExecute(Void result){
			super.onPostExecute(result);
			mDialog.cancel();
		}
		
	}
	private void init(){
		setIndicator("拨号",0,new Intent(this,HomeDialActivity.class),R.drawable.tab_dial_selected);
		setIndicator("联系人",1,new Intent(this,HomeContactActivity.class),R.drawable.tab_contact_normal);
		setIndicator("信息",2,new Intent(this,HomeSMSActivity.class),R.drawable.tab_sms_normal);
		setIndicator("设置",3,new Intent(this,HomeSettingActivity.class),R.drawable.tab_settings_normal);
		
		mTabHost.setOpenAnimation(true);
	}
	private void setIndicator(String ss,int tabId,Intent intent,int image_id){
		View localView=LayoutInflater.from(this.mTabHost.getContext()).inflate(R.layout.tab_widget_view,null);
		((ImageView)localView.findViewById(R.id.main_activity_tab_image)).setImageResource(image_id);
		((TextView)localView.findViewById(R.id.main_activity_tab_text)).setText(ss);
		String str=String.valueOf(tabId);
		TabHost.TabSpec localTabSpec=mTabHost.newTabSpec(str).setIndicator(localView).setContent(intent);
		mTabHost.addTab(localTabSpec);
	}
	private void InitImageView(){
		cursor=(ImageView)findViewById(R.id.cursor);
		bmpW=BitmapFactory.decodeResource(getResources(), R.drawable.main_tab_anim_light).getWidth();
		DisplayMetrics dm=new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);
		int screenW=dm.widthPixels;
		offset=(screenW/4-bmpW)/2;
		Matrix matrix=new Matrix();
		matrix.postTranslate(offset, 0);
		cursor.setImageMatrix(matrix);
	}
	
	private void initBottomMenu(){
		int viewCount=mTabWidget.getChildCount();
		views=new ImageView[viewCount];
		for(int i=0;i<views.length;i++){
			View v=(LinearLayout)mTabWidget.getChildAt(i);
			views[i]=(ImageView)v.findViewById(R.id.main_activity_tab_image);
		}
		mTabHost.setOnTabChangedListener(new OnTabChangeListener(){

			@Override
			public void onTabChanged(String tabId) {
				int tabID=Integer.valueOf(tabId);
				views[currIndex].setImageResource(getImageId(currIndex,false));
				views[tabID].setImageResource(getImageId(tabID,false));
				onPageSelected(tabID);
			}
			
		});
	}
	public void onPageSelected(int arg0){
		int one=offset*2+bmpW;
		Animation animation=null;
		animation=new TranslateAnimation(one*currIndex,one*arg0,0,0);
		currIndex=arg0;
		animation.setFillAfter(true);
		animation.setDuration(300);
		cursor.startAnimation(animation);
	}
	private int getImageId(int index,boolean isSelect){
		int result=-1;
		switch(index){
		case 0:
			result=isSelect?R.drawable.tab_dial_selected:R.drawable.tab_dial_normal;
			break;
		case 1:
			result=isSelect?R.drawable.tab_contact_selected:R.drawable.tab_contact_normal;
			break;
		case 2:
			result=isSelect?R.drawable.tab_sms_selected:R.drawable.tab_sms_normal;
			break;
		case 3:
			result=isSelect?R.drawable.tab_settings_selected:R.drawable.tab_settings_normal;
			break;
		}
		return result;
	}
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
		}
		return false;
	}

	protected void onDestroy() {
		super.onDestroy();
	}
	private Handler helperHandler=new Handler(){
		 @Override
		 public void handleMessage(Message msg){
			 if(mDialog!=null){
				 mDialog.dismiss();
			 }
			 try{
				 if(msg.what==VoiceHelper.WHAT_ON_CONNECT){
					 if(!VoiceApplication.getInstance().isConnect()){
						 mDialog.cancel();
						 VoiceApplication.getInstance().setConnect(true);
					 }
				 }else if(msg.what==VoiceHelper.WHAT_ON_DISCONNECT){
					 // do nothing
				 }else if(msg.what==WHAT_INIT_ERROR){
					 if(!VoiceApplication.getInstance().isConnect()){
						 showInitErrDialog();
					 }
				 }else{
					 Log4Util.d(VoiceHelper.WISDOMCALL_TAG,"Sorry , can't handle a message " + msg.what);
				 }
			 }catch(Exception e){
				 
			 }
			 super.handleMessage(msg);
		 }
	};
	
}

